package cn.skycity.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.skycity.common.mapper.SysOperLogMapper;
import cn.skycity.common.service.ISysOperLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skycity.framework.uaa.pojo.dto.SysOperLogBo;
import com.skycity.framework.uaa.pojo.entity.SysOperLog;
import com.skycity.framework.uaa.pojo.vo.SysOperLogVo;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 操作日志记录 服务实现类
 * </p>
 *
 * @author YingBo.Dai
 * @since 2024-12-05
 */
@Service
public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOperLog> implements ISysOperLogService {

    @Override
    public void cleanOperLog() {
        baseMapper.delete(Wrappers.emptyWrapper());
    }

    /**
     * 查询系统操作日志集合
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysOperLogVo> selectOperLogList(SysOperLogBo operLog) {
            LambdaQueryWrapper<SysOperLog> lqw = buildQueryWrapper(operLog);
        List<SysOperLog> logList = baseMapper.selectList(lqw.orderByDesc(SysOperLog::getId));
        return BeanUtil.copyToList(logList,SysOperLogVo.class);
    }


    private LambdaQueryWrapper<SysOperLog> buildQueryWrapper(SysOperLogBo operLog) {
        Map<String, String> params = operLog.getParams();
        return new LambdaQueryWrapper<SysOperLog>()
                .like(StrUtil.isNotBlank(operLog.getTitle()), SysOperLog::getTitle, operLog.getTitle())
                .eq(operLog.getBusinessType() != null && operLog.getBusinessType() > 0,
                        SysOperLog::getBusinessType, operLog.getBusinessType())
                .func(f -> {
                    if (ArrayUtil.isNotEmpty(operLog.getBusinessTypes())) {
                        f.in(SysOperLog::getBusinessType, Arrays.asList(operLog.getBusinessTypes()));
                    }
                })
                .eq(operLog.getStatus() != null,
                        SysOperLog::getStatus, operLog.getStatus())
                .like(StrUtil.isNotBlank(operLog.getOperator()), SysOperLog::getOperator, operLog.getOperator())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysOperLog::getCreateTime, DateUtil.parseDateTime(params.get("beginTime")), DateUtil.parseDateTime(params.get("endTime")));
    }
}
